package com.asggo.g21.config;

import com.asggo.g21.handler.DemoWebSocketHandler;
import com.asggo.g21.interceptor.WebSocketInterceptor;
import com.asggo.g21.listener.WebSocketTopicListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2023/12/15 16:11
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry
        // WebSocket 连接处理器
        .addHandler(myHandler(), "/chat")
        // WebSocket 拦截器
        .addInterceptors(webSocketInterceptor())
        // 允许跨域
        .setAllowedOrigins("*");
  }

  @Bean
  public HandshakeInterceptor webSocketInterceptor() {
    return new WebSocketInterceptor();
  }

  @Bean
  public WebSocketHandler myHandler() {
    return new DemoWebSocketHandler();
  }

  @Bean
  public WebSocketTopicListener topicListener() {
    return new WebSocketTopicListener();
  }

}
